package com.bdqn.t296.noso.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.t296.noso.entity.Role;
import com.bdqn.t296.noso.entity.User;
import com.bdqn.t296.noso.mapper.UserMapper;
import com.bdqn.t296.noso.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    UserService userService;
    @Resource
    UserMapper userMapper;

    //配置欢迎页面
    @RequestMapping("/")
    public String index(Model model, HttpServletResponse response) {
        return "login";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "login";
    }

    @RequestMapping("/403")
    public String noauth() {
        return "403";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //清空session
        session.removeAttribute("sessionuser");
        return "login";
    }


    @PostMapping(value = "/dologin")
    public String dologin(@RequestParam(value = "loginname") String loginname,
                          @RequestParam(value = "pwd") String pwd,
                          Model model,
                          HttpSession session) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("loginname",loginname);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } else {
            if (!user.getPwd().equals(pwd)) {
                model.addAttribute("msg", "密码错误");
                return "login";
            } else {
                session.setAttribute("sessionuser", user);
                return "main";
            }
        }
    }

}
